﻿Eg.Loader = Eg.Class.extend({
  status: 0,
  done: false,
  _drawStatus: 0,
  unloaded: [],
  loadCallbackBound: null,
  init: function (opts) {
    this.res = Eg.resources;
    this.gameClass = opts.GameClass;
    this.loadCallbackBound = this.loadCallback.bind(this);
    for (var i = 0; i < this.res.length; i++) {
      this.unloaded.push(this.res[i].path);
    }
  },
  addRes: function (res) {
    this.res.push(res);
    this.unloaded.push(res.path);
  },
  load: function () {
    for (var i = 0; i < this.res.length; i++) {
      this.res[i].load(this.loadCallbackBound);
    }
    this._intervalId = setInterval(this.draw.bind(this), 16);
  },
  loadCallback: function (path, status) {
    if (status) {
      this.unloaded.erase(path);
    }
    else {
      throw ('Failed to load resource: ' + path);
    }

    this.status = 1 - (this.unloaded.length / this.res.length);
    if (this.unloaded.length == 0) { // all done?
      this.done = true;
      var self = this;
      setTimeout(function () {
        clearInterval(self._intervalId);
        Eg.sys.setGame(self.gameClass);
      }, 250);
    }
  },
  draw: function () {
    this._drawStatus += (this.status - this._drawStatus) / 5;
    var w = Eg.sys.realWidth * 0.6;
    var h = Eg.sys.realHeight * 0.1;
    var x = Eg.sys.realWidth * 0.5 - w / 2;
    var y = Eg.sys.realHeight * 0.5 - h / 2;

    Eg.sys.context.fillStyle = '#000';
    Eg.sys.context.fillRect(0, 0, Eg.sys.realWidth, Eg.sys.realHeight);

    Eg.sys.context.fillStyle = '#fff';
    Eg.sys.context.fillRect(x, y, w, h);

    Eg.sys.context.fillStyle = '#000';
    Eg.sys.context.fillRect(x + 1, y + 1, w - 2, h - 2);

    Eg.sys.context.fillStyle = '#fff';
    Eg.sys.context.fillRect(x, y, w * this._drawStatus, h);
  }
});